<template>
	<div style="display: flex; align-items: center;flex-direction: column;">
		<el-form ref="ruleFormRef" style="width: 600px" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm">
			<el-form-item label="用户名" prop="userName">
				<el-input v-model="ruleForm.userName" />
			</el-form-item>
			<el-form-item label="密码" prop="userPass">
				<el-input v-model="ruleForm.userPass" />
			</el-form-item>
			<el-form-item label="可管理控数" prop="maxDeviceNum">
				<el-input v-model="ruleForm.maxDeviceNum" />
				<el-text>当前可分配控数：{{ useUser.userInfo.maxDeviceNum - isDeviceNum }}</el-text>
			</el-form-item>
			<el-form-item label="备注" prop="beiZhu">
				<el-input v-model="ruleForm.beiZhu" />
			</el-form-item>
			<el-form-item label="菜单权限" prop="permission_list">
				<el-tree ref="tree" style="max-width: 600px" :data="ruleForm.permission_list" :props="elTreeDefaultProps" node-key="name" show-checkbox />
			</el-form-item>
		</el-form>
	</div>
	<div style="display: flex; justify-content: flex-end;">
		<el-button @click="emit('close')">取消</el-button>
		<el-button type="primary" @click="onSubmit(ruleFormRef)">提交</el-button>
	</div>
</template>

<script setup>
import { reactive, ref, defineEmits,defineProps, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user.js';
import {addUser,userGetUserDeviceNumApi} from '@/api/user'
import {ElMessage} from 'element-plus'

const props = defineProps(["row"]);
const emit = defineEmits(['close']);
const tree = ref(null);
const useUser = useUserStore();
const ruleFormRef = ref();
const isDeviceNum = ref(0)
const ruleForm = reactive({
	userName: '',
	userPass: '',
	maxDeviceNum:'',
	beiZhu: '',
	permission_list: JSON.parse(useUser.userInfo.permission_list),
});

const elTreeDefaultProps = {
	children: 'children',
	label: 'name',
	disabled: 'disabled',
};

const rules = reactive({
	userName: [{ required: true, message: '请填写用户名' }],
	userPass: [{ required: true, message: '请填写密码' }],
	maxDeviceNum: [{ required: true, message: '请填写可管理控数' }],
});

const userDialogClose = () => {
	emit('close');
};

const onSubmit = async (formEl) => {
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			console.log(Number(ruleForm.maxDeviceNum),Number(useUser.userInfo.maxDeviceNum),Number(isDeviceNum.value))
			if(Number(ruleForm.maxDeviceNum) > Number(useUser.userInfo.maxDeviceNum) - Number(isDeviceNum.value)){
				return ElMessage.error('可管理控数不能大于剩余可分配控数')
			}

			const treeCheckList = tree.value.getCheckedNodes();
			let arr = [];
			for (const item of treeCheckList) {
				if (!item?.children) {
					arr.push({ name: item.name });
				}
			}
			const result = ruleForm.permission_list
				.map((item) => {
					if(item.children){
						// 对每个 item 中的 children 数组进行过滤
						const filteredChildren = item.children.filter((child) => arr.some((subItem) => subItem.name === child.name));

						// 返回新的对象，保留原结构并更新 children
						return {
							...item,
							children: filteredChildren,
						};
					}else{
						return{...item}
					}
					
				})
				let data = ruleForm
				data.permissionList = JSON.stringify(result)
				const res = await addUser(data)
				ElMessage({
					message:res.msg,
					type:res.code == 0 ? 'success' : 'error',
				})
				userDialogClose()
		} else {
			console.log('error submit!', fields);
		}
	});
};

onMounted(async() => {
	console.log(props.row)
	const result = await userGetUserDeviceNumApi({
		_id: useUser.userInfo.userId,
		userName:useUser.userInfo.userName
	})
	isDeviceNum.value = result.data.isDeviceNum
})
</script>

<style lang="scss" scoped></style>

